package com.example.attempt.controller;

import com.example.attempt.entity.Grade;
import com.example.attempt.entity.Homework;
import com.example.attempt.entity.Statistics;
import com.example.attempt.entity.Submit;
import com.example.attempt.service.impl.GradeServiceImpl;
import com.example.attempt.service.impl.HomeworkServiceImpl;
import com.example.attempt.service.impl.StatisticsServiceImpl;
import com.example.attempt.service.impl.SubmitServiceImpl;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@RestController
public class StatisticsController {
    @Autowired
    private StatisticsServiceImpl statisticsImpl;
    @Autowired
    private GradeServiceImpl gradeImpl;
    @Autowired
    private HomeworkServiceImpl homeworkImpl;
    @Autowired
    private SubmitServiceImpl submitImpl;
    @Autowired
    private CourseController courseImpl;

    @PostMapping(path = "/getStatistics")
    public Statistics getStatistics(@RequestParam(value = "hid") int hid){
        if(homeworkImpl.queryByHid(hid).getIsPublish()==0) {
            System.out.println("还没发布成绩捏");
            return null;
        }
        updateStatistics(hid);
        return statisticsImpl.getStatistics(hid);
    }

    @PostMapping(path = "/updateStatistics")
    public int updateStatistics(@RequestParam(value = "hid") int hid){
        Statistics sta = new Statistics();
        sta.setHid(hid);
        double average = gradeImpl.getAverage(hid);
        BigDecimal two = new BigDecimal(average);
        average = two.setScale(2, RoundingMode.HALF_UP).doubleValue(); //保留1位小数
        sta.setAverage(average);
        if(gradeImpl.getNum(hid,-10)!=0) //有人未评完
            return -1;
        sta.setUp90(gradeImpl.getNum(hid,90) + gradeImpl.getNum(hid, 100));
        sta.setUp80(gradeImpl.getNum(hid,80));
        sta.setUp70(gradeImpl.getNum(hid,70));
        sta.setUp60(gradeImpl.getNum(hid,60));
        sta.setDown60(gradeImpl.getDown60Num(hid));
        statisticsImpl.updateStatistics(sta);
        return 0;
    }

    @PostMapping(path = "/getStuGrade")
    public List<Grade> getStuGrade(@RequestParam(value = "cid") String cid,
                                   @RequestParam(value = "sid") String sid){
        List<Homework> homeworks = homeworkImpl.queryByCid(cid);
        List<Grade> grades = new ArrayList<>();
        for(Homework homework : homeworks){
            if(gradeImpl.getGradesByHidSid(homework.getHid(),sid)==null)
                continue;
            grades.add(gradeImpl.getGradesByHidSid(homework.getHid(),sid));
        }
        return grades;
    }

    @GetMapping(path = "/downloadGrade")
//    public ResponseEntity<FileSystemResource> downloadGrade(@RequestParam(value = "cid") String cid) throws IOException{
    public String downloadGrade(@RequestParam(value = "cid") String cid) throws IOException{
        System.out.println("----------------------下载成绩表----------------------------------");
        if(homeworkImpl.queryByCid(cid).isEmpty())
            return "http://lyycf.natapp1.cc/grade/blank.xlsx";
//            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        String mypath = "D:\\IDEA\\mutual-evaluation\\src\\main\\resources\\grade\\";
        try (Workbook workbook = new XSSFWorkbook()) {
            List<Homework> homeworks = homeworkImpl.queryByCid(cid);

            for (Homework homework : homeworks) {
                //作业未发布
                if(homework.getIsPublish()==0)
                    continue;

                //获取作业标题
                String title = homework.getTitle();

                // 创建工作表
                Sheet sheet = workbook.createSheet(title);

                // 添加表头
                Row headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("学号");
                headerRow.createCell(1).setCellValue("成绩");

                // 添加数据
                int rowNum = 1;
                List<Submit> submits = submitImpl.getByHid(homework.getHid());
                for (Submit submit : submits) {
                    String sid = submit.getSid();
                    double grade = gradeImpl.getGradesByHidSid(homework.getHid(), sid).getGrade();
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(sid);
                    row.createCell(1).setCellValue(grade);
                }
            }

            // 保存到文件
            String filename = mypath +courseImpl.getCourse(cid).getCname() + "成绩.xlsx";
            File file=new File(filename);
            if(file.exists()){
                System.out.println("删除");
                System.out.println(file.delete());
            }
            try (FileOutputStream outputStream = new FileOutputStream(filename)) {
                workbook.write(outputStream);
            }

            workbook.close();
            System.out.println("Excel导出成功！");

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 构造 FileSystemResource
        String filename = courseImpl.getCourse(cid).getCname() + "成绩.xlsx";
        String path = mypath + courseImpl.getCourse(cid).getCname() + "成绩.xlsx";
        FileSystemResource fileSystemResource = new FileSystemResource(new File(path));

        // 设置响应头，告诉浏览器这是一个文件下载
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", new String(filename.getBytes("UTF-8"), "ISO-8859-1"));

        // 返回 ResponseEntity 包含文件数据和响应头
//        return ResponseEntity.ok().headers(headers).body(fileSystemResource);

        return "http://lyycf.natapp1.cc/grade/" + filename;
    }
}
